package com.lcq.gulimall.testssocli2.controller;

import com.lcq.gulimall.testssocli2.vo.StudentVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class IndexController {
    @Value("${server.port}")
    String port;

    @RequestMapping("index.html")
    public String index(Model model, HttpSession session){
        String name = (String) session.getAttribute("user");
        if(StringUtils.isEmptyOrWhitespace(name)){
            return "redirect:http://localhost:8080/login.html?redirect_url=http://localhost:"+port+"/loginSuc";
        }
        StudentVo studentVo1 = new StudentVo();
        studentVo1.setAge(20);
        studentVo1.setName("zhangsan");
        StudentVo studentVo2 = new StudentVo();
        studentVo2.setAge(22);
        studentVo2.setName("lisi");
        List<StudentVo> list = new ArrayList<>();
        list.add(studentVo1);
        list.add(studentVo2);
        model.addAttribute("stuList",list);
        return "index";
    }

    @RequestMapping("loginSuc")
    public String loginSuc(@RequestParam("token")String token,HttpSession session){
        if (!StringUtils.isEmptyOrWhitespace(token)){
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://localhost:8080/getLoginInfo?token=" + token, String.class);
            String name = forEntity.getBody();
            session.setAttribute("user",name);
            return "redirect:http://localhost:"+port+"/index.html";
        }
        return "redirect:http://localhost:8080/login.html?redirect_url=http://localhost:"+port+"/loginSuc";
    }
}
